﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MyWPFApp
{
    public partial class MainWindow : Window
    {
        // 定义窗口过程的委托
        private HwndSourceHook? _hwndSourceHook;

        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("INVOKE AT WPF");
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            HwndSource? source = PresentationSource.FromVisual(this) as HwndSource;
            if (source != null)
            {
                // 在窗口初始化时设置窗口过程钩子
                _hwndSourceHook = new HwndSourceHook(WndProc);
                source.AddHook(_hwndSourceHook);
            }
        }

        // 窗口过程函数
        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            const int WM_GETDLGCODE = 0x0087;
            const int DLGC_WANTALLKEYS = 4;

            // 处理 WM_GETDLGCODE 消息
            if (msg == WM_GETDLGCODE)
            {
                handled = true;
                return new IntPtr(DLGC_WANTALLKEYS);
            }

            return IntPtr.Zero; // 继续传递其他消息
        }

        protected override void OnClosed(EventArgs e)
        {
            // 清理钩子
            if (_hwndSourceHook != null)
            {
                HwndSource? source = PresentationSource.FromVisual(this) as HwndSource;
                if (source != null)
                {
                    source.RemoveHook(_hwndSourceHook);
                }
            }

            base.OnClosed(e);
        }
    }
}
